import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class StudentPanel extends JPanel {
    private JTable studentTable;
    private DefaultTableModel tableModel;
    private StudentDAO studentDAO;

    public StudentPanel() {
        studentDAO = new StudentDAO();
        setLayout(new BorderLayout(10, 10));

        // 表格
        String[] columnNames = {"学号", "姓名", "性别", "班级"};
        tableModel = new DefaultTableModel(columnNames, 0);
        studentTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(studentTable);
        add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

        JButton addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAddDialog();
            }
        });
        buttonPanel.add(addButton);

        JButton editButton = new JButton("修改");
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = studentTable.getSelectedRow();
                if (selectedRow >= 0) {
                    String studentId = (String) tableModel.getValueAt(selectedRow, 0);
                    showEditDialog(studentId);
                } else {
                    JOptionPane.showMessageDialog(StudentPanel.this,
                            "请先选择要修改的学生", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        buttonPanel.add(editButton);

        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = studentTable.getSelectedRow();
                if (selectedRow >= 0) {
                    String studentId = (String) tableModel.getValueAt(selectedRow, 0);
                    int option = JOptionPane.showConfirmDialog(StudentPanel.this,
                            "确定要删除学号为 " + studentId + " 的学生吗?", "确认删除",
                            JOptionPane.YES_NO_OPTION);
                    if (option == JOptionPane.YES_OPTION) {
                        if (studentDAO.deleteStudent(studentId)) {
                            refreshTable();
                            JOptionPane.showMessageDialog(StudentPanel.this,
                                    "删除成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(StudentPanel.this,
                                    "删除失败", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(StudentPanel.this,
                            "请先选择要删除的学生", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        buttonPanel.add(deleteButton);

        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshTable();
            }
        });
        buttonPanel.add(refreshButton);

        add(buttonPanel, BorderLayout.SOUTH);

        // 查询面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        JTextField searchField = new JTextField(15);
        JButton searchButton = new JButton("查询");
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String keyword = searchField.getText();
                if (keyword.isEmpty()) {
                    refreshTable();
                } else {
                    searchStudents(keyword);
                }
            }
        });
        searchPanel.add(new JLabel("学号/姓名:"));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);
        add(searchPanel, BorderLayout.NORTH);

        // 初始化表格数据
        refreshTable();
    }

    private void refreshTable() {
        tableModel.setRowCount(0);
        List<Student> students = studentDAO.getAllStudents();
        for (Student student : students) {
            Object[] rowData = {
                    student.getStudentId(),
                    student.getName(),
                    student.getGender(),
                    student.getClassName()
            };
            tableModel.addRow(rowData);
        }
    }

    private void searchStudents(String keyword) {
        tableModel.setRowCount(0);
        List<Student> students = studentDAO.getAllStudents();
        for (Student student : students) {
            if (student.getStudentId().contains(keyword) ||
                    student.getName().contains(keyword)) {
                Object[] rowData = {
                        student.getStudentId(),
                        student.getName(),
                        student.getGender(),
                        student.getClassName()
                };
                tableModel.addRow(rowData);
            }
        }
    }

    private void showAddDialog() {
        JDialog dialog = new JDialog();
        dialog.setTitle("添加学生");
        dialog.setSize(300, 250);
        dialog.setModal(true);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(5, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JTextField idField = new JTextField();
        JTextField nameField = new JTextField();
        JComboBox<String> genderCombo = new JComboBox<>(new String[]{"男", "女"});
        JTextField classField = new JTextField();

        panel.add(new JLabel("学号:"));
        panel.add(idField);
        panel.add(new JLabel("姓名:"));
        panel.add(nameField);
        panel.add(new JLabel("性别:"));
        panel.add(genderCombo);
        panel.add(new JLabel("班级:"));
        panel.add(classField);

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Student student = new Student();
                student.setStudentId(idField.getText());
                student.setName(nameField.getText());
                student.setGender((String) genderCombo.getSelectedItem());
                student.setClassName(classField.getText());

                if (studentDAO.addStudent(student)) {
                    refreshTable();
                    dialog.dispose();
                    JOptionPane.showMessageDialog(StudentPanel.this,
                            "添加成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(StudentPanel.this,
                            "添加失败，学号可能已存在", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panel.add(saveButton);

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        panel.add(cancelButton);

        dialog.add(panel);
        dialog.setVisible(true);
    }

    private void showEditDialog(String studentId) {
        Student student = studentDAO.getStudentById(studentId);
        if (student == null) return;

        JDialog dialog = new JDialog();
        dialog.setTitle("修改学生信息");
        dialog.setSize(300, 250);
        dialog.setModal(true);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(5, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JTextField idField = new JTextField(student.getStudentId());
        idField.setEditable(false);
        JTextField nameField = new JTextField(student.getName());
        JComboBox<String> genderCombo = new JComboBox<>(new String[]{"男", "女"});
        genderCombo.setSelectedItem(student.getGender());
        JTextField classField = new JTextField(student.getClassName());

        panel.add(new JLabel("学号:"));
        panel.add(idField);
        panel.add(new JLabel("姓名:"));
        panel.add(nameField);
        panel.add(new JLabel("性别:"));
        panel.add(genderCombo);
        panel.add(new JLabel("班级:"));
        panel.add(classField);

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                student.setName(nameField.getText());
                student.setGender((String) genderCombo.getSelectedItem());
                student.setClassName(classField.getText());

                if (studentDAO.updateStudent(student)) {
                    refreshTable();
                    dialog.dispose();
                    JOptionPane.showMessageDialog(StudentPanel.this,
                            "修改成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(StudentPanel.this,
                            "修改失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panel.add(saveButton);

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        panel.add(cancelButton);

        dialog.add(panel);
        dialog.setVisible(true);
    }
}
